// 通用函数
import { nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import useClipboard from 'vue-clipboard3';
import { ElMessage } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { Local } from '/@/utils/storage';
import router from '/@/router/index';
import { store } from '/@/store/index';
import { i18n } from '/@/i18n/index';


//百分比格式化
export function percentFormat(row: any, column: number, cellValue: any) {
	return cellValue ? `${cellValue}%` : '-';
};
//列表日期时间格式化
export function dateFormatYMD(row: any, column: number, cellValue: any) {
	if (!cellValue) return '-';
	return formatDate(new Date(cellValue), 'yyyy-MM-dd');
};
//列表日期时间格式化
export function dateFormatYMDHMS(row: any, column: number, cellValue: any) {
	if (!cellValue) return '-';
	return formatDate(new Date(cellValue), 'yyyy-MM-dd HH:mm:ss');
};
//列表日期时间格式化
export function dateFormatHMS(row: any, column: number, cellValue: any) {
	if (!cellValue) return '-';
	let time = 0;
	if (typeof row === 'number') time = row;
	if (typeof cellValue === 'number') time = cellValue;
	return formatDate(new Date(time * 1000), 'HH:mm:ss');
};
// 小数格式化
export function scaleFormat(value: any = 0, scale: number = 4) {
	return Number.parseFloat(value).toFixed(scale);
};
// 小数格式化
export function scale2Format(value: any = 0) {
	return Number.parseFloat(value).toFixed(2);
};
// 点击复制文本
export function copyText(text: string) {
	const { toClipboard } = useClipboard();
	return new Promise((resolve, reject) => {
		try {
			//复制
			toClipboard(text);
			//下面可以设置复制成功的提示框等操作
			ElMessage.success('复制成功');
			resolve(text);
		} catch (e) {
			//复制失败
			ElMessage.error('复制失败');
			reject(e);
		}
	});
};
/**
 * 线性数据转成树形数据
 * @param data 数组数据[]
 * @param id default='id'
 * @param pid default='parentId'
 * @param children default='children'
 */
export function lineToTreeData(data: any, id: string, pid: string, children: string) {
	if(!data || !(data instanceof Array)){
		return null;
	}
	id = id || 'id';
	pid = pid || 'parentId';
	children = children || 'children';
	let cloneData = JSON.parse(JSON.stringify(data));

	//遍历所有数据找到所有的根节点
	let rootIds = [], results = [];
	for(let i = 0; i < cloneData.length; i++){
		let isRoot = true;
		for(let j = 0; j < cloneData.length; j++){
			if(cloneData[i][pid] == cloneData[j][id]){
				isRoot = false;
				break;
			}
		}
		if(isRoot){
			rootIds.push(cloneData[i][pid]);
		}
	}

	rootIds = Array.from(new Set(rootIds));//去重

	for(let k = 0; k < rootIds.length; k++){
		let pvalue = rootIds[k];
		let result = cloneData.filter((father: any) => {
			let arr = cloneData.filter((child: any) => father[id] == child[pid]);
			arr.length > 0 ? father[children] = arr : father[children] = undefined;
			return father[pid] == pvalue;
		});
		results.push(...result);//合并
	}

	return results;
};

/**
 * 全局组件大小
 * @returns 返回 `window.localStorage` 中读取的缓存值 `globalComponentSize`
 */
export const globalComponentSize: string = Local.get('themeConfig')?.globalComponentSize;

/**
 * 对象深克隆
 * @param obj 源对象
 * @returns 克隆后的对象
 */
export function deepClone(obj: any) {
	let newObj: any;
	try {
		newObj = obj.push ? [] : {};
	} catch (error) {
		newObj = {};
	}
	for (let attr in obj) {
		if (typeof obj[attr] === 'object') {
			newObj[attr] = deepClone(obj[attr]);
		} else {
			newObj[attr] = obj[attr];
		}
	}
	return newObj;
}

/**
 * 图片懒加载
 * @param el dom 目标元素
 * @param arr 列表数据
 * @description data-xxx 属性用于存储页面或应用程序的私有自定义数据
 */
export const lazyImgLoading = (el: any, arr: any) => {
	const io = new IntersectionObserver((res) => {
		res.forEach((v: any) => {
			if (v.isIntersecting) {
				const { img, key } = v.target.dataset;
				v.target.src = img;
				v.target.onload = () => {
					io.unobserve(v.target);
					arr[key]['loading'] = false;
				};
			}
		});
	});
	nextTick(() => {
		document.querySelectorAll(el).forEach((img) => io.observe(img));
	});
};

/**
 * 设置浏览器标题国际化
 */
export function useTitle() {
	return () => {
		nextTick(() => {
			let webTitle = '';
			let globalTitle: string = store.state.themeConfig.themeConfig.globalTitle;
			router.currentRoute.value.path === '/login'
				? (webTitle = router.currentRoute.value.meta.title as any)
				: (webTitle = i18n.global.t(router.currentRoute.value.meta.title as any));
			document.title = `${webTitle} - ${globalTitle}` || globalTitle;
		});
	};
}